<template>
    <div></div>
</template>

<script setup lang="ts" name="Callback">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getToken as getCodeToken, getInfo, logOut } from "@/api/base/token";
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus';
import { useCodeVerifierStore } from "@/store/code-verifier";
import { getPermissionsByUserId } from "@/api/base/permissions";
const userStore = useUserStore();
const router = useRouter();
const codeVerifierStore = useCodeVerifierStore();
// 定义响应式变量来存储查询参数
const code = ref<string | null>(null);
const state = ref<string | null>(null);
const issuer = ref<string | null>(null);
onMounted(async () => {
    // 获取当前 URL
    const urlParams = new URLSearchParams(window.location.search);
    // 提取查询参数
    code.value = urlParams.get("code");
    state.value = urlParams.get("state");
    issuer.value = urlParams.get("iss");
    await getToken(urlParams);
    const userInfo = await getInfo();
    const permissions = await getPermissionsByUserId(userInfo.id);
    // 发送用户信息和权限到主窗口
    window.opener && window.opener.postMessage(
        {
            type: 'auth-success',
            userInfo,
            permissions
        },
        '*'
    );
    window.close();
});

const getToken = async (urlParams: URLSearchParams) => {
    if (!code.value) {
        ElMessage.error({
            type: "danger",
            message: "授权码未找到",
        });
        return;
    }
    const codeVerifier = codeVerifierStore.codeVerifier;
    if (!codeVerifier) {
        ElMessage.error({
            type: "danger",
            message: "code_verifier未找到",
        });
        return;
    }
    const callbackPath = router.resolve({ path: "/callback" }).href;
    const absoluteCallbackUrl = window.location.origin + callbackPath;

    try {
        const params = new URLSearchParams({
            grant_type: "authorization_code",
            code: code.value,
            redirect_uri: absoluteCallbackUrl,
            client_id: import.meta.env.VITE_OPENIDDICT_CLIENT_ID,
            client_secret: import.meta.env.VITE_OPENIDDICT_CLIENT_SECRET,
            code_verifier: codeVerifier, // 必须提供！
        });
        const tokenResponse = await getCodeToken(params);
        localStorage.setItem("token", tokenResponse.access_token);
        localStorage.setItem("refresh_token", tokenResponse.refresh_token);
        return tokenResponse.access_token;
    } catch (error) {
        console.error("Error exchanging authorization code for tokens:", error);
    }
};
</script>

<style lang="scss" scoped></style>